package hydrap2p.gui.commands;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.util.*;

import hydrap2p.download.DownloadPriority;
import hydrap2p.download.Source;
import hydrap2p.gui.GUIDataHandler;
import hydrap2p.gui.GUIDownloadListing;
import hydrap2p.library.Range;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

public class Cmd_FileTransferPanel_AddBTToDownloadQueue implements Command {

	@Override
	public void execute() {
		// Get a path
		// JFileChooser for source (.torrent file)
		JFileChooser chooser = new JFileChooser();
		TorrentFileFilter filter = new TorrentFileFilter();
		boolean sel;
		File srcPath = null;
		
		do{
			sel = true;
			chooser.setDialogTitle("Select source file");
			chooser.setCurrentDirectory(new File(GUIDataHandler.DOWNLOAD_PATH));
			chooser.setFileFilter(filter);
			chooser.setMultiSelectionEnabled(false);
			
			int status = chooser.showDialog(null,"Load");
			GUIDataHandler.DOWNLOAD_PATH = chooser.getCurrentDirectory().getPath();
			
			try{
				while(srcPath == null){
					if(status == JFileChooser.CANCEL_OPTION){
						return;
					}
					if(status == JFileChooser.APPROVE_OPTION){
						if(!chooser.getSelectedFile().exists()){
							JOptionPane.showMessageDialog(null, "The specified file does not exist.\n\nPlease select a different filepath.");
							status = chooser.showDialog(null,"Load");
						}
					}
					srcPath = chooser.getSelectedFile();
					// Check filepath
					if(srcPath.getName().length() == 0){
						JOptionPane.showMessageDialog(null, "No filename entered.");
						srcPath = null;
					}else if(srcPath.getParent() == null){
						JOptionPane.showMessageDialog(null, "Invalid directory.");
						srcPath = null;
//					}else if(!srcPath.getName().endsWith(".torrent")){
//						JOptionPane.showMessageDialog(null, "The specified file is not a valid torrent file (.torrent).  Please select a file that matches this file extension.");
//						chooser.setSelectedFile(srcPath.getParentFile());
//						srcPath = null;
//						
					}
				}
				
			}catch(Exception ex){
				sel = false;
				
			}
		}while(!sel);
		
		System.out.println("Source file selected.");
		
		// JFileChooser for destination
		chooser = new JFileChooser();
		File destPath = null;
		String srcString = srcPath.getAbsolutePath();
		do{
			sel = true;
			chooser.setDialogTitle("Select destination for " + srcPath.getName());
			chooser.setSelectedFile(new File(srcString.substring(0, srcString.lastIndexOf(".torrent"))));
			chooser.setMultiSelectionEnabled(false);
			
			int status = chooser.showDialog(null,"Save");
			GUIDataHandler.DOWNLOAD_PATH = chooser.getCurrentDirectory().getPath();
			
			try{
				while(destPath == null){
					if(status == JFileChooser.CANCEL_OPTION){
						return;
					}
					if(status == JFileChooser.APPROVE_OPTION){
						if(chooser.getSelectedFile().exists()){
							JOptionPane.showMessageDialog(null, "The specified file already exists.\n\nPlease select a different filepath.");
							status = chooser.showDialog(null,"Save");
						}
					}
					destPath = chooser.getSelectedFile();
					// Check filepath
					if(destPath.getName().length() == 0){
						JOptionPane.showMessageDialog(null, "No filename entered.");
						destPath = null;
					}else if(destPath.getParent() == null){
						JOptionPane.showMessageDialog(null, "Invalid directory.");
						destPath = null;
					}
				}
				
			}catch(Exception ex){
				sel = false;
				
			}
		}while(!sel);
		
		System.out.println("Destination file selected.");
		
		try{
			// Read in .torrent file
			FileInputStream fis = new FileInputStream(srcPath);
			byte[] fileBytes = new byte[(int)srcPath.length()];
			fis.read(fileBytes);
			fis.close();
			
			// Compile torrent download info
			String protocol = "bittorrent";
			Source source = new Source();
			source.setProtocol(protocol);
			
			Map<String, ByteBuffer> attachment = new TreeMap<String, ByteBuffer>();
			attachment.put("torrent_file", ByteBuffer.wrap(fileBytes));
			source.setAttachment(attachment);
			
			Map<String, String> extra = new TreeMap<String, String>();
			extra.put("path", destPath.getAbsolutePath());
			source.setExtra(extra);
			
			List<Source> sources = new ArrayList<Source>();
			sources.add(source);
			
			GUIDataHandler.getInstance().addToDownloadQueue(sources, destPath.getParent(), destPath.getName());
			
		}catch(IOException ioe){
			System.out.println("An error occurred in processing the torrent file " + srcPath.getName() + ".");
		}
		
		System.out.println(getCommand());
		
	}

	@Override
	public String getCommand() {
		return this.getClass().getSimpleName();
	}

	@Override
	public void unexecute() {
		// TODO Auto-generated method stub

	}
	
	class TorrentFileFilter extends javax.swing.filechooser.FileFilter{
		/**
		 * Returns a boolean dictating whether or not the 
		 * @param file - The file being filtered
		 * @return Returns true if the file entered exists and its name ends in ".torrent".
		 * @return Returns false otherwise.
		 */
		public boolean accept(File file){
			if(file == null){
				return false;
			}
			
			if(file.isDirectory()){
				return true;
			}
			
			if(file.getName().toLowerCase().endsWith(".torrent")){
				return true;
			}
			
			return false;
		}
		
		/**
		 * 
		 */
		public String getDescription(){
			return "Torrent files (.torrent)";
		}
		
	}

}
